<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #box {
      padding: 20px;
      background: palegoldenrod;
    }
  </style>
</head>

<body>
  <div id="box"></div>
  <button id="btn1">执行计算任务</button>
  <button id="btn2">更改背景颜色</button>
  <script>
    var box = document.getElementById('box')
    var btn1 = document.getElementById('btn1')
    var btn2 = document.getElementById('btn2')
    var number = 99999
    var value = 0

    function calc(deadline) {
      while (number > 0
        &&
        deadline.timeRemaining() > 1// 空闲一秒以下
      ) {
        value = Math.random() < 0.5 ? Math.random() : Math.random()
        number--
        console.log('value')
      }

      // 循环条件存在，递归调用
      requestIdleCallback(calc)
    }
    function xunhuan() {
      while (number > 0
      ) {
        value = Math.random() < 0.5 ? Math.random() : Math.random()
        number--
        console.log('value')
      }

    }

    btn1.onclick = function () {
      /** 
       * 1. 计算占用js主线程
       * 2. 空闲计算
        */
      // 1
      // xunhuan()
      // 2
      requestIdleCallback(calc)
    }
    btn2.onclick = function () {
      box.style.background = 'green'
    }
  </script>
</body>

</html>